package org.example.xtong.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* org.example.xtong.controller..*.*(..))")
    public void logPointCut() {}


    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        
        // 打印请求信息
        logger.info("请求URL: {}", request.getRequestURL().toString());
        logger.info("请求方法: {}", request.getMethod());
        logger.info("请求IP: {}", request.getRemoteAddr());
        logger.info("类方法: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        logger.info("请求参数: {}", Arrays.toString(joinPoint.getArgs()));
    }


    @AfterReturning(returning = "result", pointcut = "logPointCut()")
    public void doAfterReturning(Object result) {
        logger.info("返回结果: {}", result);
    }

    // 记录方法执行时间
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();
        logger.info("方法执行时间: {} ms", endTime - startTime);
        return result;
    }
}